<?php
namespace Model;
use HY\Model;
!defined('HY_PATH') && exit('HY_PATH not defined.');
//获取系统信息
//20230219增加 系统执行任务的工具接口

class Sysinfo extends Model {
	function getIps(){
		$fp = popen('/sbin/ifconfig -a | awk \'{ print $1 " " $2  }\'', "r"); //获取ip
		$rs = "";
		//循环一直读 将返回结果放到rs中
		while(!feof($fp)){
			$rs .= fread($fp,1024);
		}
		pclose($fp);

		$rs = explode("\n \n",trim($rs));
		//return $rs;
		$return = [];
		 foreach ($rs as $k=>$v) {
		     $v = explode("\n",$v);
			 $lineIp = explode(" ",$v[1]);
			 $ethname = trim(explode(" ",$v[0])[0],":");
			 $speed = $this->execCmd('sudo /usr/sbin/ethtool -I '.$ethname.' |grep Speed');
			 $speed = trim(explode("\n",$speed)[0]);
			 
			 array_push($return,[
				 "ethname"=>$ethname,
				"ip"=> $lineIp[0]=="inet"? $lineIp[1]:"",
				'speed'=>$speed
			 ]);
		 }
		//echo $return;
		return $return;
	}
	function traceroute($tip){
		if(trim($tip) == ""){
			return [];
		}
		$cmd = "/usr/bin/traceroute ".trim($tip);

		$fp = popen($cmd, "r");
		$rs = "";
		//循环一直读 将返回结果放到rs中
		while(!feof($fp)){
			$rs .= fread($fp,1024);
		}
		pclose($fp);
		return explode("\n",trim($rs,"\n"));
	}
	//指定源目的ip ping多少次源端口 源设备口名称 目标ip（多个用空格）重复次数(默认是1)
	function ping($tips,$sip="",$sdev="",$count=1,$tout=3000){
		if(trim($tips) == ""){
			return [];
		}
		$sip = $sip==""?"":" -S ".$sip;
		$sdev = $sdev==""?"":" -I ".$sdev;
		//$cmd = "su -s /bin/bash -c \"/usr/sbin/fping -t ".$tout." -e -r ".$count.$sip.$sdev." ".$tips."\" www";
		$cmd = "/usr/sbin/fping -t ".$tout." -e -r ".$count.$sip.$sdev." ".$tips;
		//$cmd = "su -s /bin/bash -c  \"/usr/sbin/fping -v\"";
//		$out = [];
//		exec($cmd,$out,$rc);
//		var_dump($out);
//		return $rc;
		$fp = popen($cmd, "r");
		$rs = "";
		//循环一直读 将返回结果放到rs中
		while(!feof($fp)){
			$rs .= fread($fp,1024);
		}
		pclose($fp);
		return explode("\n",trim($rs,"\n"));
	}
	//单纯执行命令 返回字符串
	function execCmd($cmd){
		$fp = popen($cmd, "r");
		$rs = "";
		//循环一直读 将返回结果放到rs中
		while(!feof($fp)){
			$rs .= fread($fp,1024);
		}
		pclose($fp);
		return trim($rs);
	}

	function nohupExecCmd($cmd){
		$fp = pclose(popen('nohup '.$cmd.' &', "r"));
		return trim($fp);
	}
	function execCmdClose($cmd){
		$fp = pclose(popen($cmd, "r"));
		return trim($fp);
	}
	function getSysInfo(){
		$fp = popen('top -b -n 1 | grep -E "(Cpu|Mem|Tasks)"',"r");//获取某一时刻系统cpu和内存使用情况
		$rs = "";
		while(!feof($fp)){ $rs .= fread($fp,1024); }
		pclose($fp);
		$sys_info = explode("\n",$rs);

		//进程数据
		//$task_info = explode(",",trim($sys_info[0],'Tasks:'));
		$task_info = explode(",",$sys_info[0]);
		//正在运行的进程数
		$task_total = trim(trim($task_info[0],'total'),"Tasks:");
		$task_running = trim(trim($task_info[1],'running'));

		//CPU数据
		//us 用户空间占用CPU百分比
		//sy 内核空间占用CPU百分比
		//ni 用户进程空间内改变过优先级的进程占用CPU百分比
		//id 空闲CPU百分比
		//wa 等待输入输出的CPU时间百分比
		//hi 硬件中断
		//si 软件中断
		//st: 实时
		$cpu_info = explode(",",trim($sys_info[1]));  //CPU占有量  数组
		//CPU占有量
		$cpu_us = trim(trim($cpu_info[0],'us'),'%Cpu(s):') ;
		$cpu_sy = trim(trim($cpu_info[1],'sy')) ;
		$cpu_id = trim(trim($cpu_info[3],'id')) ;//cpu空闲百分比

		//内存
		$mem_info = explode(",",trim($sys_info[2])); //内存占有量 数组
		//内存占有量
		$mem_total = trim(trim($mem_info[0],'total'),'MiB Mem :') ;
		$mem_free = trim($mem_info[1],'free') ;
		$mem_used = trim($mem_info[2],'used') ;
		$mem_buff = trim($mem_info[3],'buff/cache') ;

		/*硬盘使用率 begin*/
		//文件系统中可用空间的总大小
		//已用空间量
		//可用空间量
		//已用空间量，表示为总容量的百分比
		$fp = popen('df -lh | grep -E "^(/)"',"r");
		$rs = fread($fp,1024);
		pclose($fp);
		//Log::info("access_token :".$rs);
	//     //把多个空格换成 “_”
		$rs = explode("\n",$rs)[0];
		$rs = preg_replace("/\s{2,}/",' ',$rs);

		$hd = explode(" ",$rs);
		//$hd = array_merge(array_unique($hd),[]);

		//Log::info("access_token :".json_encode($hd));
		$hd_total = trim($hd[1],"G"); //总大小 单位G
		$hd_use = trim($hd[2],"G"); //已用 单位G
		$hd_avail = trim($hd[3],"G"); //可用 单位G
		$hd_rate = trim($hd[4]); // 百分比
		/*硬盘使用率 end*/

		/*网络使用率*/
		/*
		if (false === ($prevVal = file("/proc/net/dev"))) {
			return false;
		}
		$result = file_get_contents("/proc/net/dev");

		preg_match("/lo:\s+\d+\s+\d+/", $result, $preg_str);
		//这里将lo 以及后边的两个数字提取出来 到preg str中

		$preg_str = explode("\n",$result);
		$preg_arr=trim(explode(':',$preg_str[3])[1]);
		$preg_arr = explode(' ',$preg_arr);

		$bytes = $preg_arr[0];
		$packets = $preg_arr[1];
		//var_dump($preg_arr);die;
		//$this->json($preg_arr);

		//$net_usage  = round($packets*100/$bytes,2);
		*/

		$all=[
				'task_total'=>$task_total,
				'task_running'=>$task_running,
				'cpu_us'=>$cpu_us,
				'cpu_sy'=>$cpu_sy,
				'cpu_id'=>$cpu_id,
				'mem_total'=>round((int)$mem_total/(1024),2),
				'mem_free'=>round((int)$mem_free/(1024),2),
				'mem_used'=>round((int)$mem_used/(1024),2),
				'mem_buff'=>round((int)$mem_buff/(1024),2),
				'hd_total'=>$hd_total,
				'hd_use'=>$hd_use,
				'hd_avail'=>$hd_avail,
				'hd_rate'=>$hd_rate,
				//'net_rate'=>$net_usage
		];
		return $all;
	}
	function request_post($url, $post_data,$headers){
		// header传送格式
		// $headers = array(
		//     "token:1111111111111",
		//     "over_time:22222222222",
		// );
		//初始化
		$curl = curl_init();
		//设置抓取的url
		curl_setopt($curl, CURLOPT_URL, $url);
		//设置头文件的信息作为数据流输出
		curl_setopt($curl, CURLOPT_HEADER, false);
		//设置获取的信息以文件流的形式返回，而不是直接输出。
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		//设置post方式提交
		curl_setopt($curl, CURLOPT_POST, true);
		// 设置post请求参数
		curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
		// 添加头信息
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		// CURLINFO_HEADER_OUT选项可以拿到请求头信息
		curl_setopt($curl, CURLINFO_HEADER_OUT, true);
		// 不验证SSL
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		//执行命令
		$data = curl_exec($curl);
		// 打印请求头信息
//        echo curl_getinfo($curl, CURLINFO_HEADER_OUT);
		//关闭URL请求
		curl_close($curl);
		//显示获得的数据
		return $data;
	}

	function request_get($url){
		// header传送格式
		$headers = array(
				
		);
		// 初始化
		$curl = curl_init();
		// 设置url路径
		curl_setopt($curl, CURLOPT_URL, $url);
		// 将 curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true) ;
		// 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
		curl_setopt($curl, CURLOPT_BINARYTRANSFER, true) ;
		// 添加头信息
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		// CURLINFO_HEADER_OUT选项可以拿到请求头信息
		curl_setopt($curl, CURLINFO_HEADER_OUT, true);
		// 不验证SSL
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		// 执行
		$data = curl_exec($curl);
		// 打印请求头信息
		//        echo curl_getinfo($curl, CURLINFO_HEADER_OUT);
		// 关闭连接
		curl_close($curl);
		// 返回数据
		return $data;
	}



}